<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>

<body>
  <script>
    class Xpromise {
      constructor(fn) {
        this.state = 'pending'
        this.callback = null
        this.value = null
        this.deferred = null
        this.resolve = this.resolve.bind(this)
        fn(this.resolve)
      }

      handle(handler) {
        if (this.state === 'pending') {
          this.deferred = handler;
          return;
        }
        if (!handler.onResolved) {
          handler.resolve(this.value);
          return;
        }
        var ret = handler.onResolved(this.value);
        handler.resolve(ret)
      }

      resolve(newValue) {
        this.value = newValue;
        this.state = 'resolved';
        if (this.deferred) {
          this.handle(this.deferred);
        }
      }

      then(onResolved) {
        return new Xpromise((resolve) => {
          this.handle({
            onResolved: onResolved,
            resolve: resolve
          });
        });
      }
    }

    var promise = new Xpromise(function (resolve) {
      resolve(1);
      resolve(2);
    });

    promise.then((res) => {
      console.log(res);
    })

  </script>
</body>

</html>